let db=require('../db/dbmanager');
const log4js        = require('../data/log');
const logger        = log4js.getLogger('db');

/**
 * 子通道数据库操作
 */
let Channel={
    updateOnline:function(parentId,deviceId,online){
        return new Promise(function (resolve, reject) {
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid: deviceId,
                $parentid: parentId,
            };
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newOrUpdateSql;
                    if (rows && rows.length) {
                        newOrUpdateSql = "UPDATE CHANNEL SET online=$online ";
                        if (online) {
                            newParam.$last_heart = (new Date()).getTime();
                            newOrUpdateSql += ", last_heart=$last_heart "
                        }
                        newOrUpdateSql += " WHERE deviceid=$deviceid AND parentid=$parentid";
                    } else {
                        newParam.$last_heart = (new Date()).getTime();
                        newOrUpdateSql = "INSERT INTO CHANNEL(deviceid,parentid,online,last_heart) VALUES ($deviceid,$parentid,$online,$last_heart)";
                    }
                    db.sqliteDB.run(newOrUpdateSql, Object.assign(newParam, {
                        $online: online
                    }));
                    resolve(rows)
                } else {
                    reject();
                }
            });
        });
    },
    // 更新截图
    updateSnap:function(snap, parentid, deviceid){
        return new Promise(function (resolve, reject) {
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid: deviceid,
                $parentid: parentid
            };
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newsql;
                    if (rows && rows.length) {
                        newsql = "UPDATE CHANNEL SET snap=$snap " +
                            " WHERE deviceid=$deviceid AND parentid=$parentid";
                    }
                    db.sqliteDB.run(newsql, Object.assign(newParam, {
                        $snap: snap
                    }));
                    resolve(rows)
                } else {
                    reject();
                }
            });
        });
    },
    /**
     * 协议变更
     * @param {*} channelInfo
     */
    updateProtocol: function(channelInfo){

    },
    // 更新设备信息，如果记录不存在就自动新增
    updateDeviceInfo: function(channelInfo){
        return new Promise(function (resolve, reject) {
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid: channelInfo.DeviceID.toString(),
                $parentid: channelInfo.ParentID.toString()
            };
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newsql;
                    if (rows && rows.length) {
                        newsql = "UPDATE CHANNEL SET online=1, " +
                            "name=$name," +
                            "manufacture=$manufacture," +
                            "model=$model," +
                            "owner=$owner," +
                            "civilcode=$civilcode," +
                            "address=$address," +
                            "registerway=$registerway," +
                            "secrecy=$secrecy," +
                            "last_heart=$last_heart," +
                            "rtsp_url=$rtsp_url" +
                            " WHERE deviceid=$deviceid AND parentid=$parentid";
                    } else {
                        // 新增
                        newsql = "INSERT INTO CHANNEL(deviceid,parentid,online,name,manufacture,model,owner,civilcode,address,registerway,secrecy,last_heart,rtsp_url) " +
                            " VALUES " +
                            "($deviceid,$parentid,1,$name,$manufacture,$model,$owner,$civilcode,$address,$registerway,$secrecy,$last_heart,$rtsp_url)";
                    }
                    if (!channelInfo.Address) {
                        channelInfo.Address = '';
                    }
                    db.sqliteDB.run(newsql, Object.assign(newParam, {
                        $name: channelInfo.Name.toString(),
                        $manufacture: channelInfo.Manufacturer.toString(),
                        $model: channelInfo.Model.toString(),
                        $owner: channelInfo.Owner.toString(),
                        $civilcode: channelInfo.CivilCode.toString(),
                        $address: channelInfo.Address.toString(),
                        $registerway: channelInfo.RegisterWay.toString(),
                        $secrecy: channelInfo.Secrecy.toString(),
                        $last_heart: (new Date()).getTime(),
                        $rtsp_url: channelInfo.rtsp_url
                    }));
                    resolve(rows)
                } else {
                    reject();
                }
            });
        });
    },
    /**
     * 查询列表
     * @param {*} parentId
     */
    list: function(parentId){
        return new Promise(function (resolve) {
            const sql = `SELECT * FROM CHANNEL WHERE parentid='${parentId}'`;
            db.sqliteDB.queryData(sql, function (rows) {
                resolve(rows);
            });
        });
    },
    // TODO: 重置状态，camera的可能要修改
    reset:function(){
        let minTime = (new Date()).getTime()-60*10*1000;
        const sql = "UPDATE CHANNEL SET online=0 WHERE last_heart<" + minTime;
        logger.log(sql);
        db.sqliteDB.run(sql);
    },
    /**
     * 根据父通道删除所有子通道信息
     * @param {*} parentId
     */
    deleteByParentId: function(parentId){
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentid";
        let paramChannel = {$parentid: parentId};
        db.sqliteDB.run(sqlChannel, paramChannel);
    },
    /**
     * 删除某个通道
     * @param parentId 设备id
     * @param deviceId 子通道
     */
    deleteByDeviceId: function(parentId, deviceId){
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentId and deviceid=$deviceId";
        let paramChannel = {$parentId: parentId, $deviceId: deviceId};
        db.sqliteDB.run(sqlChannel, paramChannel);
    }
};
module.exports=Channel;
